// 导入数据库操作模块
const { mysql } = require("../../db");
const moment = require("moment");

const formatData = (results) => {
	try {
		const data = results.map(o => ({
			...o,
			production: "《" + o.production + "》",
			animename: "《" + o.animename + "》",
			gender:
				o.gender === 0 ? "男" :
					o.gender === 1 ? "女" : "未知",
			country:
				o.country === 0 ? "国内" :
					o.country === 1 ? "日本" :
						o.country === 2 ? "欧美" : "其他",
			create: moment(o.create).format("YYYY-MM-DD HH:mm:ss")
		}));
		return data;
	} catch (err) {
		throw err;
	}
};

exports.Info = async (req, res, table) => {
	try {
		const sqlStr = `SELECT * FROM ${table} WHERE is_delete = 0`;
		const [results] = await mysql.query(sqlStr);
		if (results.length === 0) return res.cc("获取失败，无番剧信息！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

// 添加
exports.Add = async (req, res, table) => {
	const { authorname, c_name, nickname, gender, country, intro, id } = req.body;
	const info = { authorname, c_name, nickname, country, gender, intro, creator: req.user.id };
	try {
		const sqlStr = `INSERT INTO ${table} SET ?`;
		const [results] = await mysql.query(sqlStr, [info]);
		if (results.affectedRows !== 1) return res.error("新增失败");
		return res.success("新增成功");
	} catch (err) {
		return res.error(err);
	}
};

// 修改
exports.Update = async (req, res, table) => {
	const { authorname, c_name, nickname, gender, country, intro, id } = req.body;
	const info = [authorname, c_name, nickname, gender, country, intro, id];
	try {
		const sqlStr = `UPDATE ${table} SET authorname=?,c_name=?,nickname=?,gender=?,country=?,intro=? WHERE id = ?`;
		const [results] = await mysql.query(sqlStr, info);
		if (results.affectedRows !== 1) return res.error("修改失败");
		return res.success("修改成功");
	} catch (err) {
		return res.error(err);
	}
};

// 搜索
exports.Search = async (req, res, table) => {
	const info = req.params.value;

	try {
		const sqlStr = `SELECT * From ${table} WHERE (authorname LIKE ? OR c_name LIKE ? OR nickname LIKE ? OR intro LIKE ? OR country LIKE ?) AND is_delete = 0`;
		const SeletePattern = `%${info}%`;
		const values = Array(5).fill(SeletePattern);
		const [results] = await mysql.query(sqlStr, values);
		if (results.length === 0) return res.error("该作者不存在！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};